<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" 
        content="width=device-width,height=device-height,user-scalable=no,initial-scale=1.0">
    <!-- 优先使用 IE 最新版本和 Chrome -->
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <title>摇一摇</title>
    <script type="text/javascript" src="./fastclick.js"></script>
    <script type="text/javascript">
        if ('addEventListener' in document) {
            document.addEventListener('DOMContentLoaded', function() {
                FastClick.attach(document.body);
            }, false);
        }
    </script>
    <style type="text/css">
        .demo{
            width: 200px;
            height: 30px;
            appearance:button;
            -webkit-appearance:button;
        }
    </style>
</head>
<body>
<script type="text/javascript">  
    if (window.DeviceMotionEvent) {
        /* 监听传感器运动事件 */
        window.addEventListener('devicemotion', deviceMotionHandler, false);
    }else{
        alert('当前设备不支持DeviceMotion');
    }
    // 定义一个摇动的阈值
    var shakeThreshold = 1000;
    // 记录上一次摇动的时间 
    var lastUpdate = 0; 
    // 定义x、y、z记录三个轴的数据以及上一次触发的数据
    var x, y, z, lastX, lastY, lastZ; 
    // 运动传感器处理
   function deviceMotionHandler(eventData) {
       var acceleration = eventData.accelerationIncludingGravity; // 获取含重力的加速度
       var curTime = new Date().getTime();
       // 100毫秒进行一次位置判断
       if ((curTime - lastUpdate) > 100) {
           var diffTime = curTime - lastUpdate;
           lastUpdate = curTime;
           x = acceleration.x;
           y = acceleration.y;
           z = acceleration.z;
           var speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000;
           if (speed > shakeThreshold) {
              alert("摇一摇触发")
           }
           lastX = x;
           lastY = y;
           lastZ = z;
        }
    }
</script> 
</script>
</body>
</html>